package com.lzw.service.impl.admin;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lzw.mapper.admin.AdminManagementMapper;
import com.lzw.pojo.Admin;
import com.lzw.service.admin.AdminManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminManagementImpl implements AdminManagementService {

    @Autowired
    private AdminManagementMapper adminManagementMapper;

    @Override
    public List<Admin> listAll() {
        return adminManagementMapper.listAll();
    }

    @Override
    public List<Admin> list(Integer pageNum, Integer pageSize, String name, String phone) {
        PageHelper.startPage(pageNum,pageSize);
        List<Admin> list = adminManagementMapper.list(name,phone);
        Page<Admin> admins = (Page<Admin>) list;
        return admins;
    }

    @Override
    public void delete(List<Integer> ids) {
        adminManagementMapper.delete(ids);
    }

    @Override
    public Admin getAdminById(Integer id) {
        return adminManagementMapper.getAdminById(id);
    }

    @Override
    public void add(Admin admin) {
        if (adminManagementMapper.countByName(admin.getName()) > 0) {
            throw new IllegalArgumentException("管理员姓名已存在");
        }
        if (adminManagementMapper.countByUsername(admin.getUsername()) > 0) {
            throw new IllegalArgumentException("用户名已存在");
        }
        if (adminManagementMapper.countByPhone(admin.getPhone()) > 0) {
            throw new IllegalArgumentException("联系电话已存在");
        }
        adminManagementMapper.add(admin);
    }

    @Override
    public void update(Admin admin) {
        Admin existing = adminManagementMapper.getAdminById(admin.getAdminId());

        //检查学生是否存在
        if (existing == null){
            throw new IllegalArgumentException("系统管理员不存在");
        }

        // 检查姓名是否修改
        if (!existing.getName().equals(admin.getName())
                && adminManagementMapper.countByName(admin.getName()) > 0) {
            throw new IllegalArgumentException("管理员姓名已存在");
        }

        // 检查用户名是否修改
        if (!existing.getUsername().equals(admin.getUsername())
                && adminManagementMapper.countByUsername(admin.getUsername()) > 0) {
            throw new IllegalArgumentException("用户名已存在");
        }

        // 检查电话是否修改
        if (!existing.getPhone().equals(admin.getPhone())
                && adminManagementMapper.countByPhone(admin.getPhone()) > 0) {
            throw new IllegalArgumentException("联系电话已存在");
        }

        adminManagementMapper.update(admin);
    }
}
